package com.pasu.breakreminder.activities;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.pasu.breakreminder.R;
import com.pasu.breakreminder.utils.AlarmReceiver;
import com.pasu.breakreminder.utils.DialogFactory;
import com.pasu.breakreminder.utils.Logger;
import com.pasu.breakreminder.utils.PreferencesHelper;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    // alarm manager as a timer
    private AlarmManager mAlarmManager;
    // determines if alarm is turned on
    private boolean mIsOn;
    private PreferencesHelper mPrefHandler;
    private BroadcastReceiver mActivityReceiver;
    private AlertDialog mNotificationDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Logger.i(TAG, ">> onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_view);
        mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        mPrefHandler = new PreferencesHelper(this);
        boolean alreadyFirstRun = mPrefHandler.getBoolean(PreferencesHelper.PREF_ALREADY_FIRST_RUN);
        if (!alreadyFirstRun) {
            DialogFactory.createSimpleDialog(this, getString(R.string.dialog_first_run_title), getString(R.string.dialog_first_run_button_text),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                        }
                    }).show();
            mPrefHandler.save(PreferencesHelper.PREF_ALREADY_FIRST_RUN, true);
        }
        mIsOn = mPrefHandler.getBoolean(PreferencesHelper.PREF_ALARM_STATUS_ON);
        ImageView button = (ImageView) findViewById(R.id.main_button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsOn = !mIsOn;
                mPrefHandler.save(PreferencesHelper.PREF_ALARM_STATUS_ON, mIsOn);
                updateUI();
                updateWorkingStatus();
            }
        });
        updateUI();
        mActivityReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String message = mPrefHandler.getString(PreferencesHelper.Settings.General.MESSAGE);
                if (mNotificationDialog != null && mNotificationDialog.isShowing()) {
                    return;
                }
                mNotificationDialog = DialogFactory.createSimpleDialog(MainActivity.this, message != null && message.length() > 0 ? message
                        : getString(R.string.dialog_alarm_break_title), getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                mNotificationDialog.show();
            }
        };
        registerReceiver(mActivityReceiver, new IntentFilter(AlarmReceiver.ALARM_RECEIVED_INTENT_FILTER));
    }

    @Override
    protected void onDestroy() {
        Logger.i(TAG, ">> onDestroy()");
        unregisterReceiver(mActivityReceiver);
        super.onDestroy();
    }

    private void updateUI() {
        TextView label = (TextView) findViewById(R.id.main_label_top);
        ImageView button = (ImageView) findViewById(R.id.main_button);
        label.setText(mIsOn ? getString(R.string.label_is_on) : getString(R.string.label_is_off));
        button.setImageResource(mIsOn ? R.drawable.button_is_on : R.drawable.button_is_off_2);
    }

    private void updateWorkingStatus() {
        if (!mIsOn) {
            Logger.i(TAG, "cancel alarm");
            cancelAlarm();
        } else {
            Logger.i(TAG, "set alarm");
            setAlarm();
        }
    }

    public void setAlarm() {
        validateData();
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, AlarmReceiver.ALARM_RECEIVER_INTENT, intent, 0);
        int sTime = mPrefHandler.getInt(PreferencesHelper.Settings.General.TIME);
        long repeatInterval = 1000 * 15;
        if (sTime > 0) {
            repeatInterval = 1000 * 60 * sTime;
        }
        Logger.i(TAG, "set alarm with interval " + sTime + " minutes");
        mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + repeatInterval, repeatInterval, pi);
    }

    public void cancelAlarm() {
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, AlarmReceiver.ALARM_RECEIVER_INTENT, intent, 0);
        mAlarmManager.cancel(sender);
    }

    private void validateData() {
        Logger.i(TAG, ">> validateData()");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_settings:
            startActivity(new Intent(MainActivity.this, SettingsActivity.class));
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
